<template>
  <div class="product-detail-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/product/list', query: { categoryId: product.categoryId } }">
          {{ getCategoryName(product.categoryId) }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 商品基本信息区域 -->
    <div v-if="!loading" class="product-basic-info">
      <!-- 左侧图片区域 -->
      <div class="product-images">
        <!-- 缩略图列表 -->
        <div class="thumb-list">
          <div 
            v-for="(image, index) in product.images" 
            :key="index"
            class="thumb-item"
            :class="{ active: activeImageIndex === index }"
            @click="activeImageIndex = index"
          >
            <img :src="image" :alt="`${product.name}图片${index + 1}`" class="thumb-image">
          </div>
        </div>
        <!-- 主图片轮播 -->
        <div class="main-image">
          <el-carousel 
            v-model="activeImageIndex" 
            :interval="0" 
            arrow="always"
            class="image-carousel"
          >
            <el-carousel-item v-for="(image, index) in product.images" :key="index">
              <img :src="image" :alt="`${product.name}图片${index + 1}`" class="carousel-image">
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      
      <!-- 右侧商品信息 -->
      <div class="product-info">
        <!-- 商品标题 -->
        <h1 class="product-title">{{ product.name }}</h1>
        
        <!-- 商品标签 -->
        <div class="product-tags">
          <el-tag 
            v-for="(tag, index) in getProductTags(product.tags)" 
            :key="index"
            :type="getTagType(tag)"
            size="small"
          >
            {{ tag }}
          </el-tag>
        </div>
        
        <!-- 价格信息 -->
        <div class="product-price">
          <div class="price-label">价格</div>
          <div class="price-value">
            <span class="currency">¥</span>
            <span class="price-number">{{ product.price }}</span>
            <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
          </div>
        </div>
        
        <!-- 销量和评价 -->
        <div class="product-stats">
          <div class="stat-item">
            <span class="stat-label">销量：</span>
            <span class="stat-value">{{ formatNumber(product.salesVolume) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">评价：</span>
            <span class="stat-value">{{ product.reviewCount }} 条</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">评分：</span>
            <span class="stat-value">
              <el-rate :model-value="product.rating" disabled size="small" show-score score-template="{{ value }}" />
            </span>
          </div>
        </div>
        
        <!-- 商品编号 -->
        <div class="product-code">
          <span class="code-label">商品编号：</span>
          <span class="code-value">{{ product.sku }}</span>
        </div>
        
        <!-- 品牌信息 -->
        <div class="product-brand">
          <span class="brand-label">品牌：</span>
          <a :href="`/brand/detail?id=${product.brandId}`" class="brand-value">{{ getBrandName(product.brandId) }}</a>
        </div>
        
        <!-- 库存信息 -->
        <div class="product-stock">
          <span class="stock-label">库存：</span>
          <span class="stock-value" :class="{ 'low-stock': product.stock < 10 }">
            {{ product.stock }} 件
            <span v-if="product.stock < 10" class="low-stock-tip">(库存紧张)</span>
          </span>
        </div>
        
        <!-- 规格选择 -->
        <div v-if="product.specs && product.specs.length > 0" class="product-specs">
          <h3 class="specs-title">规格选择</h3>
          <div v-for="(spec, specIndex) in product.specs" :key="specIndex" class="spec-group">
            <div class="spec-label">{{ spec.name }}：</div>
            <div class="spec-options">
              <div 
                v-for="(option, optionIndex) in spec.options" 
                :key="optionIndex"
                class="spec-option"
                :class="{
                  active: selectedSpecs[spec.name] === option.value,
                  disabled: !option.available
                }"
                @click="handleSpecSelect(spec.name, option.value)"
              >
                {{ option.label }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 数量选择 -->
        <div class="product-quantity">
          <div class="quantity-label">数量：</div>
          <div class="quantity-control">
            <el-input-number 
              v-model="quantity"
              :min="1"
              :max="product.stock"
              @change="handleQuantityChange"
              class="quantity-input"
            />
            <span class="quantity-tip">
              限购{{ maxPurchaseLimit }}件
            </span>
          </div>
        </div>
        
        <!-- 配送信息 -->
        <div class="product-delivery">
          <div class="delivery-label">配送至：</div>
          <div class="delivery-value">
            <el-select 
              v-model="selectedLocation"
              placeholder="请选择配送地区"
              class="location-select"
              @change="handleLocationChange"
            >
              <el-option 
                v-for="location in deliveryLocations" 
                :key="location.id"
                :label="location.name"
                :value="location.id"
              />
            </el-select>
            <span v-if="deliveryFee > 0" class="delivery-fee">运费：¥{{ deliveryFee }}</span>
            <span v-else class="free-shipping">免运费</span>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="product-actions">
          <el-button 
            type="default" 
            @click="handleAddToCart"
            :disabled="product.stock <= 0 || !isSpecSelected"
            class="add-cart-btn"
            icon="ShoppingCart"
          >
            加入购物车
          </el-button>
          <el-button 
            type="primary" 
            @click="handleBuyNow"
            :disabled="product.stock <= 0 || !isSpecSelected"
            class="buy-now-btn"
            icon="Checkout"
          >
            立即购买
          </el-button>
          <el-button 
            type="default" 
            @click="handleAddToFavorite"
            class="favorite-btn"
            :icon="isFavorite ? 'StarFilled' : 'Star'"
            :class="{ 'is-favorite': isFavorite }"
          >
            {{ isFavorite ? '已收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>
    
    <!-- 商品详情选项卡 -->
    <div v-if="!loading" class="product-tabs">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="商品详情" name="detail" class="tab-pane">
          <div class="detail-content">
            <div v-html="product.detailContent" class="detail-html"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="规格参数" name="specs" class="tab-pane">
          <div class="specs-content">
            <table class="specs-table">
              <tbody>
                <tr v-for="(param, index) in product.parameters" :key="index">
                  <td class="param-name">{{ param.name }}</td>
                  <td class="param-value">{{ param.value }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="用户评价" name="reviews" class="tab-pane">
          <div class="reviews-content">
            <!-- 评价统计 -->
            <div class="review-summary">
              <div class="review-score">
                <div class="score-value">{{ product.rating }}</div>
                <div class="score-label">综合评分</div>
                <el-rate :model-value="product.rating" disabled size="small" />
              </div>
              <div class="review-stats">
                <div v-for="(stat, index) in reviewStats" :key="index" class="review-stat">
                  <span class="stat-label">{{ stat.label }}</span>
                  <el-progress :percentage="stat.percentage" :text-inside="true" :stroke-width="20" />
                  <span class="stat-count">{{ stat.count }} 条</span>
                </div>
              </div>
            </div>
            
            <!-- 评价筛选 -->
            <div class="review-filters">
              <el-radio-group v-model="reviewFilterType" class="review-filter-group">
                <el-radio-button label="all">全部评价</el-radio-button>
                <el-radio-button label="withImage">有图评价</el-radio-button>
                <el-radio-button label="good">好评</el-radio-button>
                <el-radio-button label="medium">中评</el-radio-button>
                <el-radio-button label="bad">差评</el-radio-button>
              </el-radio-group>
            </div>
            
            <!-- 评价列表 -->
            <div class="review-list">
              <div 
                v-for="(review, index) in reviews" 
                :key="review.id || index"
                class="review-item"
              >
                <div class="review-header">
                  <el-avatar :src="review.userAvatar || '/default-avatar.png'" class="user-avatar"></el-avatar>
                  <div class="user-info">
                    <div class="user-name">{{ review.userName }}</div>
                    <div class="review-time">{{ formatDate(review.createTime, 'yyyy-MM-dd') }}</div>
                  </div>
                  <div class="review-rating">
                    <el-rate :model-value="review.rating" disabled size="small" />
                  </div>
                </div>
                <div class="review-content">
                  <p class="review-text">{{ review.content }}</p>
                  <div v-if="review.images && review.images.length > 0" class="review-images">
                    <img 
                      v-for="(image, imgIndex) in review.images" 
                      :key="imgIndex"
                      :src="image" 
                      :alt="`评价图片${imgIndex + 1}`" 
                      class="review-image"
                    >
                  </div>
                </div>
                <div v-if="review.specInfo" class="review-spec">
                  <span class="spec-text">{{ review.specInfo }}</span>
                </div>
                <div v-if="review.replyContent" class="review-reply">
                  <div class="reply-label">商家回复：</div>
                  <div class="reply-content">{{ review.replyContent }}</div>
                </div>
              </div>
            </div>
            
            <!-- 评价分页 -->
            <div class="review-pagination">
              <el-pagination
                v-model:current-page="reviewCurrentPage"
                v-model:page-size="reviewPageSize"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="reviewTotal"
                @size-change="handleReviewSizeChange"
                @current-change="handleReviewCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="售后服务" name="service" class="tab-pane">
          <div class="service-content">
            <div class="service-item">
              <div class="service-icon">
                <el-icon><ShoppingCart /></el-icon>
              </div>
              <div class="service-info">
                <div class="service-title">退换货政策</div>
                <div class="service-description">
                  自收到商品之日起7天内，商品完好可申请7天无理由退货；15天内商品出现质量问题可申请换货。
                </div>
              </div>
            </div>
            <div class="service-item">
              <div class="service-icon">
                <el-icon><Truck /></el-icon>
              </div>
              <div class="service-info">
                <div class="service-title">配送服务</div>
                <div class="service-description">
                  全国大部分地区支持次日达，部分偏远地区可能延迟1-3天送达。
                </div>
              </div>
            </div>
            <div class="service-item">
              <div class="service-icon">
                <el-icon><HelpFilled /></el-icon>
              </div>
              <div class="service-info">
                <div class="service-title">售后服务</div>
                <div class="service-description">
                  提供7×24小时在线客服，商品质保期为1年，全国联保。
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 猜你喜欢 -->
    <div v-if="!loading && relatedProducts.length > 0" class="related-products">
      <div class="related-title">猜你喜欢</div>
      <div class="related-list">
        <ProductCard 
          v-for="relatedProduct in relatedProducts" 
          :key="relatedProduct.id"
          :product="relatedProduct"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useProductStore } from '../../store/modules/product'
import { useCartStore } from '../../store/modules/cart'
import { useUserStore } from '../../store/modules/user'
import { ArrowRight, ShoppingCart, Checkout, Star, StarFilled, HelpFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatDate, formatNumber } from '../../utils/helper'
import ProductCard from '../../components/product/ProductCard.vue'

const router = useRouter()
const route = useRoute()
const productStore = useProductStore()
const cartStore = useCartStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const product = ref({
  id: null,
  name: '',
  sku: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  salesVolume: 0,
  rating: 0,
  reviewCount: 0,
  images: [],
  categoryId: null,
  brandId: null,
  tags: [],
  specs: [],
  parameters: [],
  detailContent: '',
  description: ''
})
const activeImageIndex = ref(0)
const selectedSpecs = ref({})
const quantity = ref(1)
const selectedLocation = ref('')
const deliveryFee = ref(0)
const isFavorite = ref(false)
const activeTab = ref('detail')
const reviewStats = ref([])
const reviews = ref([])
const reviewTotal = ref(0)
const reviewCurrentPage = ref(1)
const reviewPageSize = ref(10)
const reviewFilterType = ref('all')
const relatedProducts = ref([])

// 常量
const maxPurchaseLimit = 10
const deliveryLocations = ref([
  { id: '1', name: '北京市' },
  { id: '2', name: '上海市' },
  { id: '3', name: '广州市' },
  { id: '4', name: '深圳市' },
  { id: '5', name: '杭州市' }
])

// 分类列表
const categoryList = ref([
  { id: 1, name: '手机数码' },
  { id: 2, name: '电脑办公' },
  { id: 3, name: '家用电器' },
  { id: 4, name: '智能家居' },
  { id: 5, name: '服饰鞋包' },
  { id: 6, name: '美妆个护' },
  { id: 7, name: '食品生鲜' },
  { id: 8, name: '图书文具' }
])

// 品牌列表
const brandList = ref([
  { id: 1, name: '品牌1' },
  { id: 2, name: '品牌2' },
  { id: 3, name: '品牌3' },
  { id: 4, name: '品牌4' },
  { id: 5, name: '品牌5' },
  { id: 6, name: '品牌6' },
  { id: 7, name: '品牌7' },
  { id: 8, name: '品牌8' }
])

// 计算属性：是否已选择所有规格
const isSpecSelected = computed(() => {
  if (!product.value.specs || product.value.specs.length === 0) {
    return true
  }
  return product.value.specs.every(spec => selectedSpecs.value.hasOwnProperty(spec.name))
})

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

// 获取品牌名称
const getBrandName = (brandId) => {
  const brand = brandList.value.find(b => b.id === brandId)
  return brand ? brand.name : '未知品牌'
}

// 获取商品标签
const getProductTags = (tags) => {
  const tagMap = {
    'new': '新品',
    'hot': '热销',
    'discount': '折扣',
    'freeShipping': '包邮',
    'guarantee': '正品保障'
  }
  return tags.map(tag => tagMap[tag] || tag)
}

// 获取标签类型
const getTagType = (tag) => {
  const typeMap = {
    '新品': 'primary',
    '热销': 'success',
    '折扣': 'danger',
    '包邮': 'info',
    '正品保障': 'warning'
  }
  return typeMap[tag] || 'default'
}

// 处理规格选择
const handleSpecSelect = (specName, specValue) => {
  selectedSpecs.value[specName] = specValue
  // 实际项目中可能需要根据选择的规格更新价格、库存等信息
}

// 处理数量变化
const handleQuantityChange = (value) => {
  if (value > product.value.stock) {
    quantity.value = product.value.stock
    ElMessage.warning(`最多只能购买${product.value.stock}件`)
  } else if (value > maxPurchaseLimit) {
    quantity.value = maxPurchaseLimit
    ElMessage.warning(`最多只能购买${maxPurchaseLimit}件`)
  }
}

// 处理地区选择
const handleLocationChange = (locationId) => {
  // 模拟根据地区计算运费
  // 实际项目中应该调用API获取运费信息
  deliveryFee.value = locationId === '1' ? 0 : 10
}

// 加入购物车
const handleAddToCart = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (!isSpecSelected.value) {
    ElMessage.warning('请选择完整规格')
    return
  }
  
  try {
    cartStore.addToCart({
      productId: product.value.id,
      quantity: quantity.value,
      specs: selectedSpecs.value
    })
    ElMessage.success('加入购物车成功')
  } catch (error) {
    ElMessage.error('加入购物车失败：' + error.message)
  }
}

// 立即购买
const handleBuyNow = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (!isSpecSelected.value) {
    ElMessage.warning('请选择完整规格')
    return
  }
  
  // 存储待结算商品信息
  cartStore.setCheckoutItems([{
    productId: product.value.id,
    quantity: quantity.value,
    specs: selectedSpecs.value
  }])
  
  // 跳转到结算页面
  router.push('/order/checkout')
}

// 添加收藏
const handleAddToFavorite = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 模拟收藏/取消收藏操作
  // 实际项目中应该调用API
  isFavorite.value = !isFavorite.value
  ElMessage.success(isFavorite.value ? '收藏成功' : '取消收藏成功')
}

// 处理评价分页大小变化
const handleReviewSizeChange = (size) => {
  reviewPageSize.value = size
  reviewCurrentPage.value = 1
  loadReviews()
}

// 处理评价页码变化
const handleReviewCurrentChange = (page) => {
  reviewCurrentPage.value = page
  loadReviews()
}

// 加载商品详情
const loadProductDetail = async (productId) => {
  loading.value = true
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await productStore.getProductDetail(productId)
    // product.value = data
    
    // 模拟商品数据
    product.value = generateMockProduct(productId)
    
    // 重置选择状态
    selectedSpecs.value = {}
    quantity.value = 1
    
    // 加载评价数据
    await loadReviews()
    
    // 加载相关商品
    await loadRelatedProducts()
    
    // 检查是否已收藏
    checkFavoriteStatus()
  } catch (error) {
    ElMessage.error('加载商品详情失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载评价数据
const loadReviews = async () => {
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await productStore.getProductReviews(product.value.id, {
    //   page: reviewCurrentPage.value,
    //   pageSize: reviewPageSize.value,
    //   filterType: reviewFilterType.value
    // })
    // reviews.value = data.list
    // reviewTotal.value = data.total
    // reviewStats.value = data.stats
    
    // 模拟评价数据
    reviews.value = generateMockReviews()
    reviewTotal.value = reviews.value.length
    reviewStats.value = [
      { label: '好评', percentage: 85, count: Math.floor(reviewTotal.value * 0.85) },
      { label: '中评', percentage: 10, count: Math.floor(reviewTotal.value * 0.10) },
      { label: '差评', percentage: 5, count: Math.floor(reviewTotal.value * 0.05) }
    ]
  } catch (error) {
    ElMessage.error('加载评价数据失败：' + error.message)
  }
}

// 加载相关商品
const loadRelatedProducts = async () => {
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await productStore.getRelatedProducts(product.value.id)
    // relatedProducts.value = data
    
    // 模拟相关商品数据
    relatedProducts.value = generateMockRelatedProducts()
  } catch (error) {
    ElMessage.error('加载相关商品失败：' + error.message)
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  if (!userStore.isLoggedIn) {
    isFavorite.value = false
    return
  }
  
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await productStore.checkFavorite(product.value.id)
    // isFavorite.value = data.isFavorite
    
    // 模拟收藏状态
    isFavorite.value = false
  } catch (error) {
    console.error('检查收藏状态失败：', error)
  }
}

// 生成模拟商品数据
const generateMockProduct = (productId) => {
  // 根据productId生成不同的模拟商品数据
  const productMap = {
    '1': {
      id: 1,
      name: '超级智能手机 Pro Max',
      sku: 'SKU10001',
      price: 6999,
      originalPrice: 7999,
      stock: 156,
      salesVolume: 5230,
      rating: 4.8,
      reviewCount: 1256,
      images: [
        '/product/hot1.png',
        '/product/hot1-2.png',
        '/product/hot1-3.png',
        '/product/hot1-4.png'
      ],
      categoryId: 1,
      brandId: 1,
      tags: ['new', 'hot', 'guarantee'],
      specs: [
        {
          name: '颜色',
          options: [
            { label: '暗夜黑', value: 'black', available: true },
            { label: '星空蓝', value: 'blue', available: true },
            { label: '樱花粉', value: 'pink', available: true },
            { label: '金色', value: 'gold', available: false }
          ]
        },
        {
          name: '内存',
          options: [
            { label: '8GB+128GB', value: '8+128', available: true },
            { label: '8GB+256GB', value: '8+256', available: true },
            { label: '12GB+256GB', value: '12+256', available: true },
            { label: '12GB+512GB', value: '12+512', available: true }
          ]
        }
      ],
      parameters: [
        { name: '品牌', value: '品牌1' },
        { name: '型号', value: 'Pro Max' },
        { name: '上市日期', value: '2023-06' },
        { name: '屏幕尺寸', value: '6.7英寸' },
        { name: '分辨率', value: '2778 x 1284像素' },
        { name: 'CPU型号', value: '骁龙8 Gen 2' },
        { name: '摄像头', value: '5000万像素主摄 + 1200万像素超广角 + 1200万像素长焦' },
        { name: '电池容量', value: '4500mAh' },
        { name: '充电功率', value: '65W有线快充 + 50W无线快充' },
        { name: '操作系统', value: 'Android 13' }
      ],
      detailContent: `
        <div class="detail-section">
          <h3>产品介绍</h3>
          <p>超级智能手机 Pro Max 是一款全新旗舰级智能手机，搭载最新一代处理器，提供卓越的性能和流畅的用户体验。</p>
          <img src="/product/detail/detail1.jpg" alt="产品介绍图">
        </div>
        <div class="detail-section">
          <h3>屏幕与显示</h3>
          <p>6.7英寸超视网膜XDR显示屏，支持120Hz刷新率，HDR10+认证，带来极致的视觉体验。</p>
          <img src="/product/detail/detail2.jpg" alt="屏幕展示图">
        </div>
        <div class="detail-section">
          <h3>摄影系统</h3>
          <p>全新的专业摄影系统，包括5000万像素主摄、1200万像素超广角和1200万像素长焦镜头，支持8K视频录制。</p>
          <img src="/product/detail/detail3.jpg" alt="摄像头展示图">
        </div>
        <div class="detail-section">
          <h3>性能与电池</h3>
          <p>搭载最新一代骁龙8 Gen 2处理器，配合大容量内存，性能强劲。4500mAh大容量电池，支持65W有线快充和50W无线快充。</p>
          <img src="/product/detail/detail4.jpg" alt="性能展示图">
        </div>
      `,
      description: '超级智能手机 Pro Max，旗舰体验，尽在掌握。'
    }
  }
  
  // 如果没有对应ID的商品，返回默认商品
  return productMap[productId] || productMap['1']
}

// 生成模拟评价数据
const generateMockReviews = () => {
  return [
    {
      id: 1,
      userName: '张**',
      userAvatar: '/avatar/user1.png',
      content: '手机非常好用，运行流畅，拍照效果也很棒，续航能力强，值得购买！',
      images: ['/review/review1-1.png', '/review/review1-2.png'],
      rating: 5,
      createTime: '2023-06-15 10:30:00',
      specInfo: '颜色：暗夜黑，内存：8GB+256GB',
      replyContent: '感谢您的好评，我们会继续努力提供更好的产品和服务！'
    },
    {
      id: 2,
      userName: '李**',
      userAvatar: '/avatar/user2.png',
      content: '手机整体不错，拍照清晰，系统流畅，就是价格有点高。',
      images: ['/review/review2-1.png'],
      rating: 4,
      createTime: '2023-06-10 15:45:00',
      specInfo: '颜色：星空蓝，内存：12GB+256GB'
    },
    {
      id: 3,
      userName: '王**',
      userAvatar: '/avatar/user3.png',
      content: '电池续航确实不错，一天重度使用没问题，充电也很快。',
      images: [],
      rating: 5,
      createTime: '2023-06-05 09:20:00',
      specInfo: '颜色：暗夜黑，内存：8GB+128GB'
    },
    {
      id: 4,
      userName: '陈**',
      userAvatar: '/avatar/user4.png',
      content: '收到的手机包装完好，外观很漂亮，使用体验很好，客服也很热情。',
      images: ['/review/review4-1.png', '/review/review4-2.png', '/review/review4-3.png'],
      rating: 5,
      createTime: '2023-06-01 14:15:00',
      specInfo: '颜色：樱花粉，内存：8GB+256GB'
    },
    {
      id: 5,
      userName: '赵**',
      userAvatar: '/avatar/user5.png',
      content: '手机是正品，和描述的一样，用了几天感觉不错，推荐购买。',
      images: [],
      rating: 4,
      createTime: '2023-05-28 11:30:00',
      specInfo: '颜色：暗夜黑，内存：12GB+512GB'
    }
  ]
}

// 生成模拟相关商品数据
const generateMockRelatedProducts = () => {
  return [
    {
      id: 3,
      name: '智能手表 Series 7',
      image: '/product/hot3.png',
      price: 2199,
      originalPrice: 2499,
      rating: 4.7,
      reviewCount: 765,
      salesVolume: '4000+'
    },
    {
      id: 4,
      name: '无线蓝牙耳机 Pro',
      image: '/product/hot4.png',
      price: 1299,
      originalPrice: 1499,
      rating: 4.6,
      reviewCount: 987,
      salesVolume: '6000+'
    },
    {
      id: 5,
      name: '全新旗舰手机 Ultra',
      image: '/product/new1.png',
      price: 8999,
      originalPrice: 9999,
      rating: 4.9,
      reviewCount: 123,
      salesVolume: '1000+'
    },
    {
      id: 10,
      name: '无线充电器 15W快充',
      image: '/product/discount2.png',
      price: 129,
      originalPrice: 199,
      rating: 4.5,
      reviewCount: 567,
      salesVolume: '8000+'
    }
  ]
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    loadProductDetail(newId)
  }
}, { immediate: true })

// 监听评价筛选类型变化
watch(reviewFilterType, () => {
  reviewCurrentPage.value = 1
  loadReviews()
})

// 组件挂载时加载数据
onMounted(() => {
  if (route.params.id) {
    loadProductDetail(route.params.id)
  }
})
</script>

<style scoped>
.product-detail-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin: 20px 0;
}

/* 商品基本信息区域 */
.product-basic-info {
  display: flex;
  gap: 40px;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 30px;
  margin-bottom: 30px;
}

/* 左侧图片区域 */
.product-images {
  display: flex;
  gap: 20px;
  flex-shrink: 0;
}

.thumb-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.thumb-item {
  width: 80px;
  height: 80px;
  border: 2px solid transparent;
  border-radius: $border-radius-small;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.thumb-item:hover,
.thumb-item.active {
  border-color: $primary-color;
}

.thumb-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.main-image {
  flex: 1;
  max-width: 500px;
}

.image-carousel {
  height: 500px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 右侧商品信息 */
.product-info {
  flex: 1;
  min-width: 0;
}

.product-title {
  font-size: $font-size-xxl;
  color: $text-color;
  font-weight: bold;
  line-height: 1.4;
  margin-bottom: 16px;
}

.product-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

/* 价格信息 */
.product-price {
  background-color: #fff2f0;
  padding: 16px;
  border-radius: $border-radius-base;
  margin-bottom: 20px;
}

.price-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin-bottom: 8px;
}

.price-value {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.currency {
  font-size: $font-size-xl;
  color: $danger-color;
}

.price-number {
  font-size: $font-size-xxxl;
  color: $danger-color;
  font-weight: bold;
}

.original-price {
  font-size: $font-size-base;
  color: $text-color-placeholder;
  text-decoration: line-through;
  margin-left: 12px;
}

/* 销量和评价 */
.product-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.stat-value {
  font-size: $font-size-sm;
  color: $text-color;
}

/* 商品编号、品牌、库存 */
.product-code,
.product-brand,
.product-stock {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.code-label,
.brand-label,
.stock-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  width: 80px;
}

.code-value,
.brand-value,
.stock-value {
  font-size: $font-size-sm;
  color: $text-color;
  flex: 1;
}

.brand-value {
  color: $primary-color;
  text-decoration: none;
}

.brand-value:hover {
  text-decoration: underline;
}

.low-stock {
  color: $danger-color;
}

.low-stock-tip {
  font-size: $font-size-xs;
}

/* 规格选择 */
.product-specs {
  margin-bottom: 20px;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.specs-title {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 16px;
}

.spec-group {
  margin-bottom: 16px;
}

.spec-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin-bottom: 12px;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.spec-option {
  padding: 8px 16px;
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
  cursor: pointer;
  transition: all 0.3s;
  font-size: $font-size-sm;
  color: $text-color;
}

.spec-option:hover:not(.disabled) {
  border-color: $primary-color;
  color: $primary-color;
}

.spec-option.active {
  border-color: $primary-color;
  background-color: #e6f7ff;
  color: $primary-color;
}

.spec-option.disabled {
  color: $text-color-placeholder;
  cursor: not-allowed;
}

/* 数量选择 */
.product-quantity {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.quantity-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  width: 80px;
}

.quantity-control {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.quantity-input {
  width: 120px;
}

.quantity-tip {
  font-size: $font-size-xs;
  color: $text-color-placeholder;
}

/* 配送信息 */
.product-delivery {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.delivery-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  width: 80px;
}

.delivery-value {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.location-select {
  width: 180px;
}

.delivery-fee {
  font-size: $font-size-sm;
  color: $text-color;
}

.free-shipping {
  font-size: $font-size-sm;
  color: $success-color;
}

/* 操作按钮 */
.product-actions {
  display: flex;
  gap: 16px;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.add-cart-btn,
.buy-now-btn,
.favorite-btn {
  padding: 12px 24px;
  font-size: $font-size-base;
}

.add-cart-btn {
  flex: 1;
  max-width: 200px;
}

.buy-now-btn {
  flex: 1;
  max-width: 200px;
}

.favorite-btn {
  border: 1px solid $border-color;
  color: $text-color-secondary;
}

.favorite-btn.is-favorite {
  color: $warning-color;
  border-color: $warning-color;
}

/* 加载状态 */
.loading-container {
  min-height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  margin-bottom: 30px;
}

/* 商品详情选项卡 */
.product-tabs {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  margin-bottom: 30px;
}

.detail-tabs {
  width: 100%;
}

.tab-pane {
  padding: 30px;
}

/* 详情内容 */
.detail-content {
  line-height: 1.8;
}

.detail-html {
  font-size: $font-size-base;
  color: $text-color;
}

.detail-html h3 {
  font-size: $font-size-xl;
  color: $text-color;
  margin: 20px 0 16px 0;
}

.detail-html p {
  margin-bottom: 16px;
  color: $text-color-secondary;
}

.detail-html img {
  max-width: 100%;
  height: auto;
  margin: 16px 0;
  border-radius: $border-radius-base;
}

/* 规格参数内容 */
.specs-content {
  overflow-x: auto;
}

.specs-table {
  width: 100%;
  border-collapse: collapse;
}

.specs-table td {
  padding: 12px 16px;
  border-bottom: 1px solid $border-color;
}

.param-name {
  width: 120px;
  font-size: $font-size-sm;
  color: $text-color-secondary;
  font-weight: 500;
}

.param-value {
  font-size: $font-size-sm;
  color: $text-color;
  white-space: nowrap;
}

/* 评价内容 */
.reviews-content {
  padding-top: 20px;
}

/* 评价统计 */
.review-summary {
  display: flex;
  gap: 40px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid $border-color;
}

.review-score {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding-right: 40px;
  border-right: 1px solid $border-color;
}

.score-value {
  font-size: 48px;
  color: $primary-color;
  font-weight: bold;
  line-height: 1;
}

.score-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.review-stats {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.review-stat {
  display: flex;
  align-items: center;
  gap: 12px;
}

.review-stat .stat-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  width: 60px;
}

.review-stat .el-progress {
  flex: 1;
  max-width: 300px;
}

.review-stat .stat-count {
  font-size: $font-size-sm;
  color: $text-color-placeholder;
  width: 80px;
  text-align: right;
}

/* 评价筛选 */
.review-filters {
  margin-bottom: 20px;
}

.review-filter-group {
  width: 100%;
}

/* 评价列表 */
.review-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.review-item {
  padding-bottom: 24px;
  border-bottom: 1px solid $border-color;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.review-header .user-avatar {
  width: 40px;
  height: 40px;
}

.review-header .user-info {
  flex: 1;
}

.review-header .user-name {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
}

.review-header .review-time {
  font-size: $font-size-xs;
  color: $text-color-placeholder;
}

.review-header .review-rating {
  flex-shrink: 0;
}

.review-content {
  margin-bottom: 12px;
}

.review-text {
  font-size: $font-size-base;
  color: $text-color;
  line-height: 1.6;
  margin-bottom: 12px;
}

.review-images {
  display: flex;
  gap: 8px;
}

.review-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: $border-radius-small;
  cursor: pointer;
  transition: transform 0.3s;
}

.review-image:hover {
  transform: scale(1.05);
}

.review-spec {
  margin-bottom: 12px;
}

.spec-text {
  font-size: $font-size-sm;
  color: $text-color-placeholder;
  background-color: $fill-color;
  padding: 4px 8px;
  border-radius: $border-radius-small;
}

.review-reply {
  background-color: $fill-color-light;
  padding: 12px;
  border-radius: $border-radius-base;
}

.reply-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin-bottom: 4px;
}

.reply-content {
  font-size: $font-size-sm;
  color: $text-color;
}

/* 评价分页 */
.review-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 售后服务内容 */
.service-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.service-item {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  padding: 20px;
  border-radius: $border-radius-base;
  background-color: $fill-color-light;
}

.service-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: $primary-color;
  color: #fff;
  border-radius: 50%;
  font-size: 24px;
}

.service-info {
  flex: 1;
}

.service-title {
  font-size: $font-size-lg;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 8px;
}

.service-description {
  font-size: $font-size-base;
  color: $text-color-secondary;
  line-height: 1.6;
}

/* 猜你喜欢 */
.related-products {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 30px;
  margin-bottom: 30px;
}

.related-title {
  font-size: $font-size-xl;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid $primary-color;
}

.related-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-basic-info {
    flex-direction: column;
    gap: 30px;
  }
  
  .main-image {
    max-width: 100%;
  }
  
  .image-carousel {
    height: 400px;
  }
  
  .related-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .product-basic-info {
    padding: 20px;
  }
  
  .product-title {
    font-size: $font-size-xl;
  }
  
  .price-number {
    font-size: $font-size-xxl;
  }
  
  .image-carousel {
    height: 350px;
  }
  
  .product-stats {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .review-summary {
    flex-direction: column;
    gap: 20px;
  }
  
  .review-score {
    padding-right: 0;
    border-right: none;
    border-bottom: 1px solid $border-color;
    padding-bottom: 20px;
  }
  
  .related-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .product-detail-container {
    padding: 0 10px;
  }
  
  .product-basic-info {
    padding: 16px;
  }
  
  .product-images {
    flex-direction: column;
  }
  
  .thumb-list {
    flex-direction: row;
    overflow-x: auto;
    padding-bottom: 8px;
  }
  
  .thumb-item {
    flex-shrink: 0;
  }
  
  .image-carousel {
    height: 300px;
  }
  
  .product-actions {
    flex-direction: column;
  }
  
  .add-cart-btn,
  .buy-now-btn,
  .favorite-btn {
    max-width: 100%;
  }
  
  .tab-pane {
    padding: 20px 16px;
  }
  
  .related-products {
    padding: 20px 16px;
  }
  
  .related-list {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .product-title {
    font-size: $font-size-lg;
  }
  
  .price-number {
    font-size: $font-size-xl;
  }
  
  .image-carousel {
    height: 250px;
  }
  
  .product-quantity,
  .product-delivery {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .quantity-label,
  .delivery-label,
  .code-label,
  .brand-label,
  .stock-label {
    width: auto;
  }
  
  .location-select {
    width: 100%;
  }
  
  .spec-options {
    gap: 8px;
  }
  
  .spec-option {
    padding: 6px 12px;
    font-size: $font-size-xs;
  }
}
</style>